<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="入库单编号" prop="recptCode">
        <el-input
          v-model="queryParams.recptCode"
          placeholder="请输入入库单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>



<!--      <el-form-item label="供应商名称" prop="vendorName">
        <el-input
          v-model="queryParams.vendorName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="入库日期" prop="recptDate">
        <el-date-picker clearable
          v-model="queryParams.recptDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择入库日期">
        </el-date-picker>
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <div style="height: 15px"></div>
    <el-card style="border-radius: 10px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:wm:outsourcerecpt:add']"
        >新增</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="outsourcerecptList" @selection-change="handleSelectionChange">

      <el-table-column label="入库单编号" align="center" prop="recptCode" >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['mes:wm:outsourcerecpt:query']"
          >{{scope.row.recptCode}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="入库单名称" align="center" prop="recptName" />
      <el-table-column label="生产商编码" align="center" prop="vendorCode" />
      <el-table-column label="生产商名称" align="center" prop="vendorName" />
      <el-table-column label="入库日期" align="center" prop="recptDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recptDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-video-play"
              v-if="scope.row.status =='PREPARE'"
              @click="handleExecute(scope.row)"
              v-hasPermi="['mes:wm:outsourcerecpt:edit']"
            >执行入库</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-if="scope.row.status =='PREPARE'"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['mes:wm:outsourcerecpt:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-if="scope.row.status =='PREPARE'"
              @click="handleDelete(scope.row)"
              v-hasPermi="['mes:wm:outsourcerecpt:remove']"
            >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>
    <!-- 添加或修改外协入库单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库单编号" prop="recptCode">
              <el-input v-model="form.recptCode" :readonly="optType != 'add'" placeholder="请输入入库单编号" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="入库单名称" prop="recptName">
              <el-input v-model="form.recptName"  :readonly="optType == 'view'" placeholder="请输入入库单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库批次号" prop="batchCode">
              <el-input v-model="form.batchCode" placeholder="请输入入库批次号" :readonly="optType != 'add'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库日期" prop="recptDate">
              <el-date-picker clearable :readonly="optType == 'view'"
                              v-model="form.recptDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择入库日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
            <el-col :span="8">
              <el-form-item label="有效期" prop="expireDate">
                <el-date-picker clearable
                                :readonly="optType == 'view'"
                                v-model="form.expireDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择有效期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          <el-col :span="8">
            <el-form-item label="外协生产商" prop="vendorName">
              <el-input v-model="form.vendorName" placeholder="请选择外协生产商" :readonly="true" >
                <el-button slot="append" icon="el-icon-search" v-if="optType == 'add'" @click="handleManufactureSelect"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          </el-row>
        <el-divider content-position="center">工单产品信息</el-divider>
           <el-card>
            <el-row :gutter="10" class="mb8" >
              <el-col :span="1.5">
                  <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleWorkorderSelect"
                   :disabled="!((optType == 'add' || optType == 'edit')&&form.vendorId!=null)"
                    v-hasPermi="['mes:wm:outsourcerecpt:add']"
                  >新增</el-button>
              </el-col>
            </el-row>

          <el-table border v-loading="loading" :data="form.line2" :header-cell-style="{textAlign:'center'}" :cell-style="{textAlign:'center'}">
            <el-table-column label="工单编码" width="150" prop="workorderCode" >
            </el-table-column>
            <el-table-column label="工单名称" width="120" prop="workorderName" :show-overflow-tooltip="true"/>
            <el-table-column label="产品编号" width="150" prop="productCode" />
            <el-table-column label="产品名称" width="120" prop="productName" :show-overflow-tooltip="true"/>
            <el-table-column label="规格型号" prop="productSpc" :show-overflow-tooltip="true"/>
            <el-table-column
              v-for="col in columnsConfig"
              :key="col.prop"
              :label="col.label"
              :prop="col.prop"
              :width="col.width"
              :align="col.align"
              v-if="col.show">
            </el-table-column>
            <el-table-column label="单位（主）" prop="unitOfMeasure" fixed="right"/>
            <el-table-column label="入库数量（主）" prop="quantityRecived" width="150" fixed="right">
              <template slot-scope="scope">
                <el-input-number
                                 :step="0.01"
                                 :precision="2"
                                 type="number"
                                 size="mini" :min="0.01" v-model="scope.row.quantityRecived"
                                 @change="computeIssue1(scope.row)"
                :disabled="optType=='view'"
                />
              </template>
            </el-table-column>
            <el-table-column label="单位（辅）" align="center" prop="storageUnit" fixed="right"/>
            <el-table-column label="入库数量（辅）" align="center" prop="storageUnitQuantity" width="150" fixed="right">
              <template slot-scope="scope">
                <el-input-number
                  v-if="scope.row.enableMultiUnit === 'Y'"
                  size="mini"
                  :min="0.01"
                  :disabled="optType=='view'"
                  :step="0.01"
                  :precision="2"
                  @change="computeIssue2(scope.row)"
                  v-model="scope.row.storageUnitQuantity"
                 />
              </template>
            </el-table-column>
            <el-table-column label="入库仓库" align="center" prop="warehouseId" width="320" fixed="right">
              <template slot-scope="scope">
                <el-cascader v-model="scope.row.warehouseInfo"
                             :disabled="optType == 'view'"
                             :options="warehouseOptions"
                             :props="warehouseProps"
                             @change="(val) => handleWarehouseChanged(val,  scope.row)"
                             style="width: 100%"
                >
                </el-cascader>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
              v-if="optType == 'add' || optType == 'edit' ">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  v-if="(optType == 'add' || optType == 'edit')"
                  @click="handleDeleteLine(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <SelectManufacture ref="mfSelect" :oldManufactureId="form.vendorId" :manufacture="manufacture"
                         @onSelected="onManufactureSelected"></SelectManufacture>
      <WorkorderSelect ref="woSelect" :needAdded="needAdded" :needRemove="form.line2" :selectedRowsFromP="this.form.line2" :workorder="{manufactureId:form.vendorId}"   @onSelected="onWorkorderSelected"></WorkorderSelect>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType =='view' || form.status !='PREPARE' ">返回</el-button>
        <el-button type="primary" @click="submitForm" v-if="form.status =='PREPARE' && optType !='view' ">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { addOutsourcerecpt, delOutsourcerecpt, execute, getOutsourcerecpt, listOutsourcerecpt, updateOutsourcerecpt } from "@/api/mes/wm/outsourcerecpt";
import { genCode } from "@/api/system/autocode/rule"
import WorkorderSelect from "./selectworkorder.vue"
import IqcSelect from "@/components/iqcSelect/single.vue";
import Itemrecptline from "./line.vue";
import {getTreeList} from "@/api/mes/wm/warehouse";
import SelectManufacture from "@/views/mes/md/outsourcedmanufacture/selectManufacture.vue";
import Template from "@/views/print/printtemplate/list.vue";
import {getColumnsConfigKey} from "@/api/system/columnsconfig";
export default {
  name: "Outsourcerecpt",
  dicts:['mes_order_status','sys_yes_no'],
  components :{Template, SelectManufacture, WorkorderSelect,IqcSelect,Itemrecptline},
  data() {
    return {
      columnsConfig:[],
      needAdded: [],
      warehouseInfo:[],
      warehouseOptions:[],
      warehouseProps:{
        multiple: false,
        value: 'pId',
        label: 'pName',
      },
      //自动生成编码
      autoGenFlag2:false,
      optType: undefined,
      manufacture: {enableFlag: 'Y', manufactureId: null},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 外协入库单表格数据
      outsourcerecptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        recptCode: null,
        recptName: null,
        iqcId: null,
        iqcCode: null,

        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        recptDate: null,
        status: null,
      },
      // 表单参数
      form: {

      },
      // 表单校验
      rules: {
        recptCode: [
          { required: true, message: "入库单编号不能为空", trigger: "blur" }
        ],

        vendorName: [
          { required: true, message: "请选择外协生产商", trigger: "blur" }
        ],
        recptDate:[
          { required: true, message: "入库日期不能为空", trigger: "blur" }
        ],
        "warehouseId": [
          { required: true, message: "请选择入库的仓库" }
        ],
        "batchCode": [
          { required: true, message: "入库批次号不能为空" }
        ],
    /*    "line.iqcCheck": [
          { required: true, message: "是否检验不能为空" }
        ],*/
        "expireDate": [
          { required: true, message: "有效期不能为空" }
        ],

      }
    };
  },
  created() {
    this.getList();
    this.getWarehouseList();
    this.getItemBase();
  },

  methods: {
    computeIssue1(row){
      if(row.enableMultiUnit==='Y'){
        if(row.storageUnitType==='fixed'){
          if(row.storageRatio){
            row.storageUnitQuantity=row.quantityRecived/row.storageRatio;
          }
        }
      }
    },
    computeIssue2(row){
      if(row.enableMultiUnit==='Y'){
        if(row.storageUnitType==='fixed'){
          if(row.storageRatio){
            row.quantityRecived=row.storageUnitQuantity*row.storageRatio;
          }
        }
      }
    },
    getItemBase(){
      getColumnsConfigKey('MdItem_Base').then(res=>{
        this.columnsConfig = JSON.parse(res.data);
      })
    },
    handleDeleteLine(row){
      if(row.recptId) {
        this.needAdded.push(row);
      }
      this.form.line2=this.form.line2.filter(obj => obj.workorderCode != row.workorderCode)
    },
    getWarehouseList(){
      getTreeList().then( response =>{
        if(response.data){
          this.warehouseOptions = response.data.filter((el) =>{
            return el.warehouseCode.indexOf('VIR') == -1;
          });;
        }
        this.warehouseOptions.map(w =>{
          w.children.map(l =>{
            let lstr =JSON.stringify(l.children).replace(/locationId/g,'lId').replace(/areaId/g, 'pId').replace(/areaName/g,'pName');
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g,'wId').replace(/locationId/g, 'pId').replace(/locationName/g,'pName');
          w.children =  JSON.parse(wstr);

        });
        let ostr=JSON.stringify(this.warehouseOptions).replace(/warehouseId/g,'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
      });
    },
    //选择仓库、库区、库位
    handleWarehouseChanged(obj,row){
      if(obj !=null){
        row.warehouseId = obj[0];
        row.locationId = obj[1];
        row.areaId = obj[2];
      }
    },
    /** 查询外协入库单列表 */
    getList() {
      this.loading = true;
      listOutsourcerecpt(this.queryParams).then(response => {
        this.outsourcerecptList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // 表单重置
    reset() {
      this.form = {
        batchCode: null,
        recptId: null,
        recptCode: null,
        recptName: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null, areaCode: null, areaName: null, recptDate: new Date(),
        status: "PREPARE", remark: null, attr1: null, attr2: null, attr3: null, attr4: null, createBy: null, createTime: null, updateBy: null, updateTime: null,
        line2: []
      };
      this.autoGenFlag2 = false;
        this.resetForm("form");
        this.warehouseInfo=[];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recptId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.title = "添加外协入库单";
      this.optType = "add";
      genCode('OUTSOURCE_RECPT_CODE').then(response =>{
        this.form.recptCode = response;
      });
      genCode('BATCH_CODE_NEW').then(response => {
        this.form.batchCode = response;
      });
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recptId = row.recptId || this.ids
      getOutsourcerecpt(recptId).then(response => {
        response.data.line2.forEach( obj=>{
          obj.warehouseInfo = [];
          obj.warehouseInfo[0] = obj.warehouseId;
          obj.warehouseInfo[1] = obj.locationId;
          obj.warehouseInfo[2] = obj.areaId;
        })
        this.form =response.data;
        this.open = true;
        this.title = "修改外协入库单";
        this.optType = "edit";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.line2.length==0){
            this.$modal.msgError("请选择工单产品！");
            return
          }
          this.form.line2.forEach(item=>{
            if(!item.quantityRecived||item.quantityRecived==''){
              valid=false
              this.$modal.msgError("请输入入库数量！");
              return
            }
            if('Y'===item.enableMultiUnit){
              if(!item.storageUnitQuantity||item.storageUnitQuantity==''){
                valid=false
                this.$modal.msgError("请输入入库数量（辅）！");
                return
              }
            }
          })
          if(valid) {

            if (this.form.recptId != null) {
              updateOutsourcerecpt(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addOutsourcerecpt(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recptIds = row.recptId || this.ids;
      this.$modal.confirm('是否确认删除外协入库单编号为"' + row.recptCode + '"的数据项？').then(function() {
        return delOutsourcerecpt(recptIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 查询明细按钮操作
    handleView(row){
      this.reset();
      const recptIds = row.recptId;
      getOutsourcerecpt(recptIds).then(response => {
        response.data.line2.forEach( obj=>{
          obj.warehouseInfo = [];
          obj.warehouseInfo[0] = obj.warehouseId;
          obj.warehouseInfo[1] = obj.locationId;
          obj.warehouseInfo[2] = obj.areaId;
        })
        this.form =response.data;
        this.open = true;
        this.title = "查看外协入库单信息";
        this.optType = "view";
      });
    },
    //执行入库
    handleExecute(row){
      const recptIds = row.recptId || this.ids;
      this.$modal.confirm('确认执行入库？').then(function() {
        return execute(recptIds)//执行入库
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("入库成功");
      }).catch(() => {});
    },

    //选择生产工单
    handleWorkorderSelect(){
      if(this.form.vendorId==null){
        this.$message.warning("请先选择外协生产商!")
        return
      }
      this.$refs.woSelect.showFlag = true;
      this.$refs.woSelect.getList();
    },

    handleManufactureSelect() {
      this.manufacture.manufactureId = this.form.vendorId;
      this.$refs.mfSelect.showFlag = true;
      this.$refs.mfSelect.getList();
    },
    onManufactureSelected(row) {

      if (row != undefined && row != null) {
        this.form.vendorId = row.manufactureId;
        this.form.vendorCode = row.manufactureCode;
        this.form.vendorName = row.manufactureName;
  /*      this.form.contact = row.contact1;
        this.form.contactTel = row.contact1Tel;*/
      }
    },
    onWorkorderSelected(rows){
    /*  rows.forEach(l=>{
        l.quantityRecived=l.quantityQualified
        if(l.enableMultiUnit=='Y'){
          if(l.storageUnitType=='fixed'){
            l.storageUnitQuantity=(l.quantityQualified/l.storageRatio).toFixed(2)
          }
        }
      })*/
      rows.forEach(l=>{
        l.warehouseInfo=[]
        l.warehouseInfo[0] = l.warehouseId;
        l.warehouseInfo[1] = l.locationId;
        l.warehouseInfo[2] = l.areaId;
      })
      this.form.line2.push(...rows);

    },

  }
};
</script>
